package com.tju.ocean_ecology_website.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tju.ocean_ecology_website.dto.ActivityDetailResponseDTO;
import com.tju.ocean_ecology_website.dto.ApiResponse;
import com.tju.ocean_ecology_website.entity.Activity;
import com.tju.ocean_ecology_website.entity.ActivityDetail;
import com.tju.ocean_ecology_website.entity.ActivityFeedback;
import com.tju.ocean_ecology_website.entity.ActivitySignup;
import com.tju.ocean_ecology_website.entity.User;
import com.tju.ocean_ecology_website.mapper.UserMapper;
import com.tju.ocean_ecology_website.dao.ActivityDetailDao;
import com.tju.ocean_ecology_website.service.ActivityDetailService;
import com.tju.ocean_ecology_website.service.ActivityFeedbackService;
import com.tju.ocean_ecology_website.service.ActivityService;
import com.tju.ocean_ecology_website.service.ActivitySignupService;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 志愿者活动详情控制器
 */
@RestController
@RequestMapping("/api/volunteer")
public class VolunteerActivityDetailController {

    @Resource
    private ActivityService activityService;

    @Resource
    private ActivityDetailService activityDetailService;

    @Resource
    private ActivityDetailDao activityDetailDao;

    @Resource
    private ActivitySignupService activitySignupService;

    @Resource
    private ActivityFeedbackService activityFeedbackService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ObjectMapper objectMapper;

    /**
     * 获取活动详情
     *
     * @param id 活动ID
     * @return 活动详情
     */
    @GetMapping("/activities/{id}")
    public ResponseEntity<ApiResponse<ActivityDetailResponseDTO>> getActivityDetail(@PathVariable("id") Long id) {
        // 查询活动基本信息
        Activity activity = activityService.queryById(id);
        if (activity == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "活动不存在"));
        }

        // 查询活动详情
        ActivityDetail activityDetail = null;
        try {
            ActivityDetail detailQuery = new ActivityDetail();
            detailQuery.setActivityId(id);
            // 直接使用DAO层查询，避免使用queryByPage方法
            List<ActivityDetail> details = activityDetailDao.queryAllByLimit(detailQuery, org.springframework.data.domain.PageRequest.of(0, 1));
            if (!details.isEmpty()) {
                activityDetail = details.get(0);
            }
        } catch (Exception e) {
            // 如果查询出错，记录日志并继续执行
            System.err.println("Error querying activity detail: " + e.getMessage());
            e.printStackTrace();
        }

        // 获取当前用户ID
        Long currentUserId = getCurrentUserId();

        // 查询用户是否已报名
        boolean isJoined = false;
        ActivitySignup signupQuery = new ActivitySignup();
        signupQuery.setActivityId(id);
        signupQuery.setUserId(currentUserId);
        List<ActivitySignup> signups = activitySignupService.queryAll(signupQuery);
        if (!signups.isEmpty()) {
            isJoined = true;
        }

        // 查询用户是否已提交反馈
        boolean hasFeedback = false;
        ActivityFeedback feedback = activityFeedbackService.queryByUserAndActivity(currentUserId, id);
        if (feedback != null) {
            hasFeedback = true;
        }

        // 构建响应DTO
        ActivityDetailResponseDTO responseDTO = new ActivityDetailResponseDTO();
        BeanUtils.copyProperties(activity, responseDTO);

        // 设置开始时间（与日期相同）
        responseDTO.setStartTime(activity.getDate());

        // 设置用户参与状态
        responseDTO.setIsJoined(isJoined);
        responseDTO.setHasFeedback(hasFeedback);

        // 设置活动安排和注意事项
        if (activityDetail != null) {
            // 解析活动安排
            List<ActivityDetailResponseDTO.ScheduleItem> scheduleItems = parseSchedule(activityDetail.getSchedule());
            responseDTO.setSchedule(scheduleItems);

            // 解析注意事项
            List<String> notices = parseNotices(activityDetail.getNotices());
            responseDTO.setNotices(notices);
        } else {
            // 如果没有详情数据，设置默认值
            responseDTO.setSchedule(getDefaultSchedule());
            responseDTO.setNotices(getDefaultNotices());
        }

        return ResponseEntity.ok(ApiResponse.success(responseDTO));
    }

    /**
     * 解析活动安排
     *
     * @param scheduleJson 活动安排JSON字符串
     * @return 活动安排列表
     */
    private List<ActivityDetailResponseDTO.ScheduleItem> parseSchedule(String scheduleJson) {
        if (scheduleJson == null || scheduleJson.isEmpty()) {
            return getDefaultSchedule();
        }

        try {
            return objectMapper.readValue(scheduleJson, new TypeReference<List<ActivityDetailResponseDTO.ScheduleItem>>() {});
        } catch (JsonProcessingException e) {
            // 如果解析失败，返回默认值
            return getDefaultSchedule();
        }
    }

    /**
     * 解析注意事项
     *
     * @param noticesJson 注意事项JSON字符串
     * @return 注意事项列表
     */
    private List<String> parseNotices(String noticesJson) {
        if (noticesJson == null || noticesJson.isEmpty()) {
            return getDefaultNotices();
        }

        try {
            return objectMapper.readValue(noticesJson, new TypeReference<List<String>>() {});
        } catch (JsonProcessingException e) {
            // 如果解析失败，返回默认值
            return getDefaultNotices();
        }
    }

    /**
     * 获取默认活动安排
     *
     * @return 默认活动安排列表
     */
    private List<ActivityDetailResponseDTO.ScheduleItem> getDefaultSchedule() {
        return Arrays.asList(
                ActivityDetailResponseDTO.ScheduleItem.builder().time("09:00").content("签到集合").build(),
                ActivityDetailResponseDTO.ScheduleItem.builder().time("09:30").content("活动介绍与安全须知").build(),
                ActivityDetailResponseDTO.ScheduleItem.builder().time("10:00").content("开始活动").build(),
                ActivityDetailResponseDTO.ScheduleItem.builder().time("12:00").content("午餐休息").build(),
                ActivityDetailResponseDTO.ScheduleItem.builder().time("13:30").content("继续活动").build(),
                ActivityDetailResponseDTO.ScheduleItem.builder().time("15:30").content("活动总结").build(),
                ActivityDetailResponseDTO.ScheduleItem.builder().time("16:00").content("活动结束，合影留念").build()
        );
    }

    /**
     * 获取默认注意事项
     *
     * @return 默认注意事项列表
     */
    private List<String> getDefaultNotices() {
        return Arrays.asList(
                "请穿着舒适的衣物和防滑鞋",
                "自备防晒用品和饮用水",
                "活动提供基本工具和午餐",
                "请遵守工作人员指导，注意安全",
                "活动结束后请带走个人垃圾"
        );
    }

    /**
     * 获取当前登录用户的ID
     *
     * @return 当前用户ID
     */
    private Long getCurrentUserId() {
        // 从 SecurityContextHolder 获取当前认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            // 获取用户名
            String username = authentication.getName();
            // 通过用户名查询用户信息
            User user = userMapper.findByUsername(username);
            if (user != null) {
                return user.getId();
            }
        }
        // 如果无法获取用户信息，抛出异常
        throw new RuntimeException("未能获取当前用户信息，请确保用户已登录");
    }
}
